/* @(#)heart.hh
 * Time-stamp: <2009-02-11 17:56:03 root>
 * Copyright 2008 Julian Qian
 * Author: root@localhost.localdomain
 * Version: $Id: heart.hh,v 0.0 2008/11/16 10:27:44 root Exp $
 * Keywords: 
 */

#ifndef _HEART_H
#define _HEART_H 1

// #include <ext/hash_map>
// #include <map>

// #include "common.hh"

#define SHM_HEART_SEG "heart_shared_memory"
#define SHM_HEART_OBJ "heart_obj" 


#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <utility>

// using namespace boost::interprocess;

#include "proto.hh"

// class Proto;
class Db;
class Wrapesms;

#ifndef BI
#define BI boost::interprocess
#endif

typedef std::pair<const devid_t, Proto> HPPair;

typedef BI::allocator <HPPair, BI::managed_shared_memory::segment_manager> HPShmemAllocator;

typedef BI::map <devid_t, Proto, std::less<devid_t>, HPShmemAllocator> HeartMap;


// #define HASH __gnu_cxx

// #define HEART_PAIR HASH::hash_map <devid_t, Proto*>

class Heart {
public:
    static void initHeart(HeartMap* _hMap);
    static Heart *theHeart(); // Singleton
    static void endHeart();
    
    void push_heart(Proto& pro);
    void active_heart();
    void clean_heart();
    
    int proto_nums();
    
    // update status in database
    void dblog_record(Proto& pro);
    void dblog_online(devid_t devid);
    void dblog_offline(devid_t devid);

    Proto* get_proto(devid_t devid);
    ip_t get_ip(devid_t devid);
    static stat_t check_proto(devid_t devid);
    static void print_protos();
    // void runloop();
    bool auth_db(devid_t devid);
    alarm_t get_last_alarm_db(devid_t devid);

private:
    Heart(HeartMap* hmap);
    virtual ~Heart();

    int get_lognum(devid_t did);
    
    static Heart* _theHeart;
    
    Db* _db;
    Wrapesms* _we;
    HeartMap* _hMap;

    // BI::offset_ptr<HeartMap> _hMap;
};

#endif /* _HEART_H */

